import React, {FC, useCallback, useEffect, useMemo, useRef, useState} from "react";
import "./css/ForwardModal.less";
import {Button, Input, Spin} from "antd";
import SelectTransfer from "../../module/dataForm/SelectTransfer.tsx";
import {closeModal, updataModalFooter} from "../../services/ModalService.tsx";
import {useTranslation} from "react-i18next";
import {coreDispatch} from "../../utils/StoreUtil";
import SelectModal from "./select/SelectModal";
import {getLanguageById} from "../../../i18n/i18n";
import useStateRef from "../../customUse/useStateRef.tsx";
import {createFetchParams} from "../../utils";
import Config from "../../Config";
import {AxiosDelete, AxiosGet, AxiosPost, AxiosPut, AxiosSer} from "../../services/HttpService.tsx";

interface ForwardModalProps {
    modalKey: string,
    menuId: string,
    method: string,
    userTreeApi: any,
    isNeedSignFor: boolean,
    isNeedForward: boolean,
    isNeedSignForAndForward: boolean,
    isNeedQualityInspection: boolean,
    isNeedTeam: boolean,
    isMessBool?: any
}

const ForwardModal: FC<ForwardModalProps> = (props) => {

    const {t} = useTranslation();

    const transferRef = useRef(),
        selectRowsRef = useRef([]),
        dataSourceRef = useRef([]),
        commentRef = useRef("");

    const [loading, setLoading] = useState<boolean>(true),
        [selectRows, setSelectRows] = useStateRef([], selectRowsRef),
        [dataSource, setDataSource] = useStateRef(undefined, dataSourceRef),
        [comment, setComment] = useStateRef("", commentRef);

    const mergeAndDeduplicate = (data, rows) => {
        const existingIds = new Set(data.map(item => item.contactId));
        const newRows = rows.filter(row => !existingIds.has(row.contactId));
        return [...data, ...newRows];
    }

    const loadData = useCallback(async (rows = []) => {
        setLoading(true);
        const {data = []} = await AxiosGet("/sf-drs/notice/userContact", {});
        const newData = mergeAndDeduplicate(data, rows);
        const newSelectRows = mergeAndDeduplicate(selectRowsRef.current, rows);
        setLoading(false);
        setDataSource(newData)
        setSelectRows(newSelectRows)
    }, [])

    useEffect(() => {
        loadData();
    }, []);

    const getUrlByType = useCallback((type = "forward", props) => {
        switch (type) {
            case "forward":
                return {
                    url: props.forwardUrl,
                    typeProps: props.forwardProps || {}
                };
            case "signFor":
                return {
                    url: props.signForUrl,
                    typeProps: props.signForProps || {}
                };
            case "signForAndForward":
                return {
                    url: props.signForAndForwardUrl,
                    typeProps: props.signForAndForwardProps || {}
                };
            case "qualityInspection":
                return {
                    url: props.qualityInspectionUrl,
                    typeProps: props.qualityInspectionProps || {}
                };
            case "team":
                return {
                    url: props.teamUrl,
                    typeProps: props.teamProps || {}
                };
        }
    }, []);

    const onOk = useCallback(async (type = "forward") => {
        const selectData = transferRef.current?.getSelectRows() || [];
        const {url, typeProps = {}} = getUrlByType(type, props);
        const {params = {}} = createFetchParams({...props, ...typeProps, selectData});
        setLoading(true);
        const {isMessBool = true} = props;
        const result = await AxiosSer(url, props.method || "POST", {
            ...params,
            comment: commentRef.current,
            [Config.axiosSerMenuKey]: props.menuId
        }, isMessBool);
        setLoading(false);
        result.code == "1" && await closeModal(props.modalKey, async () => {
            return result;
        });
    }, []);

    useEffect(() => {
        let btns = [<Button key="cancel"
                            onClick={() => {
                                closeModal(props.modalKey, false)
                            }}>{t("cancel")}</Button>]
        if (props.isNeedSignForAndForward) {
            btns.unshift(<Button color="cyan" variant="solid"
                                 onClick={() => (onOk("signForAndForward"))}>{t("signForAndForward")}</Button>)
        }
        if (props.isNeedForward) {
            btns.unshift(<Button type="primary" onClick={() => (onOk("forward"))}>{t("forward")}</Button>)
        }
        if (props.isNeedSignFor) {
            btns.unshift(<Button type="primary" onClick={() => (onOk("signFor"))}>{t("signFor")}</Button>)
        }
        if (props.isNeedQualityInspection) {
            btns.unshift(<Button type="primary"
                                 onClick={() => (onOk("qualityInspection"))}>{t("qualityInspection")}</Button>)
        }
        if (props.isNeedTeam) {
            btns.unshift(<Button type="primary" onClick={() => (onOk("team"))}>{t("team")}</Button>)
        }
        updataModalFooter(props.modalKey, btns)
    }, []);

    const handleTop = useCallback(async () => {
        const rows = transferRef.current?.getLeftSelectRows() || [];
        if (!rows.length) {
            return
        }
        const {code} = await AxiosPut("/sf-drs/notice/userContact/topContact", {ids: rows.map(i => i.contactId)});
        if (code == "1") {
            const select = transferRef.current?.getSelectRows() || [];
            loadData(select);
        }
    }, []);

    const handleAddCommonly = useCallback((isAddCommonly = false) => {
        coreDispatch("modalReducer/createModal", {
            key: `add-commonly-user`,
            modalProps: {
                title: t("addUser"),
                width: 500,
                okText: getLanguageById(isAddCommonly ? "addCommonlyUser" : "addUser"),
            },
            component: SelectModal,
            comProps: {
                isTreeTable: true,
                isLazyData: true,
                autoExpand: true,
                rowKey: "seqID",
                rowSelection: "multiple",
                tableApi: props.userTreeApi || {
                    url: '/sf-drs/platform/sfOrgs/specificGroupTrees',
                    params: {needDefaultGroup: false}
                },
                viewName: "col_common_name_list"
            },
            onFinish: async (res: any) => {
                if (res && res.data) {
                    let ids = [];
                    const rows = res.data.map(i => {
                        ids.push(i.id);
                        return {
                            contactId: i.id,
                            contactName: i.name
                        }
                    })
                    if (isAddCommonly) {
                        await AxiosPost("/sf-drs/notice/userContact/addContact", {ids});
                    }
                    const select = transferRef.current?.getSelectRows() || [];
                    loadData([...select, ...rows]);
                }
            }
        });
    }, [props.userTreeApi]);

    const handleRemoveCommonly = useCallback(async () => {
        const rows = transferRef.current?.getLeftSelectRows() || [];
        if (!rows.length) {
            return
        }
        const {code} = await AxiosDelete("/sf-drs/notice/userContact/deleteUserContact", {ids: rows.map(i => i.contactId)});
        if (code == "1") {
            const select = transferRef.current?.getSelectRows() || [];
            loadData(select);
        }
    }, []);

    const renderForwardModal = useMemo(() => {
        return (
            <Spin spinning={loading} wrapperClassName="sf_core_forward_modal">
                <div className="sf_core_forward_modal_transfer">
                    <SelectTransfer
                        init={transferRef}
                        width={400}
                        height={400}
                        transferField={[]}
                        titles={[
                            <div>
                                <Button size="small" onClick={handleTop} style={{marginRight: 5}}>{t("top")}</Button>
                                <Button size="small" onClick={() => (handleAddCommonly(true))}
                                        style={{marginRight: 5}}>{t("addCommonly")}</Button>
                                <Button size="small" onClick={handleRemoveCommonly}>{t("removeCommonly")}</Button>
                            </div>,
                            <Button size="small" onClick={() => handleAddCommonly(false)}>{t("addUser")}</Button>
                        ]}
                        dataSource={dataSource}
                        value={selectRows.map(i => i.contactId).join(",")}
                        format={{
                            key: "contactId",
                            label: "contactName"
                        }}
                    />
                </div>
                <div className="sf_core_forward_modal_desc">
                    <div className="sf_core_forward_modal_desc_label">
                        <span>{t("comments")}</span>
                        <span style={{color: "red", marginLeft: 20}}>{t("notExceed")}</span>
                    </div>
                    <Input.TextArea value={comment} onChange={(e) => (setComment(e.target.value))} rows={4}/>
                </div>
            </Spin>
        )
    }, [dataSource, selectRows, comment]);

    return (renderForwardModal);
};

export default React.memo(ForwardModal);